package com.wk.worksetter.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.graphics.drawable.Drawable
import android.util.Log
import com.wk.worksetter.BaseApplication
import com.wk.worksetter.TAG
import java.lang.Exception

/**
 * @author peng
 * @date 2021/1/28
 * 说明
 */
object WorkUtil {

    @SuppressLint("QueryPermissionsNeeded")
    fun getAllInstalledApps(): List<PackageInfo> {
        val pm = BaseApplication.ins.packageManager
        val installedApplications = pm.getInstalledPackages(0)
        return installedApplications.filter { it.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0 }
    }

    fun getAppLabelName(packageInfo:PackageInfo):String{
        return try {
            val applicationInfo = packageInfo.applicationInfo
            applicationInfo.loadLabel(BaseApplication.ins.packageManager).toString()
        }catch (e:Exception){
            ""
        }
    }

    fun getAppIcon(packageInfo:PackageInfo):Drawable?{
        return try {
            val applicationInfo = packageInfo.applicationInfo
            applicationInfo.loadIcon(BaseApplication.ins.packageManager)
        }catch (e:Exception){
            null
        }
    }

    /**
     * 根据包的信息启动对应app
     */

    fun launchByPackage(context: Context,packageName: String){
        val intent = context.packageManager.getLaunchIntentForPackage(packageName)
        if(context is Application) {
            intent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        context.startActivity(intent)
    }

}